import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Row,
  Col,
  Form,
  Input,
  Select,
  Button,
  PageHeader,
  message,
  Table, Tag, Collapse,
  Descriptions, Avatar, Pagination, Empty, Spin, DatePicker, Tabs, Typography, Drawer,
} from 'antd';
import styles from './Index.less';
import Card from '@material-ui/core/Card';
import request from '@/utils/request';
import echarts from 'echarts';
import ReactEcharts from 'echarts-for-react';
const FormItem = Form.Item;
const Option = Select.Option;

/* eslint react/no-multi-comp:0 */
@connect(({ whole_data2, loading, system_configs }) => ({
  whole_data2, system_configs,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.timer = null;
  }

  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    page: 1,
    per_page: 30,
    dev_eui: '',
    name: '',
    editRecord: {},
    current: 0,
    refresh_second: 1,
    stepData: {},
    mqttInfo: {},
    events: [],
    collapse_key: [],
    start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD 00:00:00"),
    end_date: moment().format('YYYY-MM-DD HH:mm:ss'),
    expend: 'expend',
    expandedRowKeys: [],
    sort_field: 'timestamp',
    sort_type: 'desc',
    rtuId: '%',
    data: [],
    searchText:''
  };


  componentDidMount() {
    let params = {};
    params = {
      page: 1,
      per_page: 30,
      start_date: this.state.start_date,
      end_date: this.state.end_date,
      // start_date: '2019-09-30',
      rtuId: '%',
      sort_field: this.state.sort_field,
      sort_type: this.state.sort_type,

    };
    const that = this;
    that.handleSearch(params, true);

    request(`/all_substrate_types`, {
      method: 'GET',
      params: {
        order_direction: 'desc',
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }
    });
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    const { dispatch } = this.props;
    dispatch({
      type: 'whole_data2/loadedPage',
      payload: true,
    });
  }


  handleSearch = (values, controlExpend) => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'whole_data2/fetch',
      payload: {
        // ...values,
        sort: 'maxTime,desc',
        timeFrom:values.start_date,
        timeUntil:values.end_date,
        rtuId: values.rtuId,
        size:1000
      },
      callback: function() {
        console.log('handleSearch callback');
        that.setState({
          ...values,
          size: values.per_page,
          page: Number(values.page) - 1,
          searchText:''
        });
      },
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      page: 1,
      per_page: 30,
      substrate_serial_number: '',
      substrate_type_id: '',
      rtuId: '%',
      start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD 00:00:00"),
      end_date: moment().format('YYYY-MM-DD HH:mm:ss'),
    });
  };


  disabledEndDate = endValue => {
    const { start_date } = this.state;
    if (!endValue || !start_date) {
      return false;
    }
    return (endValue.valueOf() <= moment(start_date).valueOf()) || (moment(endValue).format('MM') !== moment(start_date).format('MM')) || (endValue.valueOf() > moment().valueOf());
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form layout="inline">
        {/*<FormItem label={'产品码'}>
          {getFieldDecorator('product_code')(<Input placeholder=""/>)}
        </FormItem>*/}
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(this.state.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(this.state.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem>
          <Button icon="search" type="primary" onClick={() => {
            const { form } = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              const values = {
                ...fieldsValue,
              };
              let params = {
                start_date: moment(values.start_date).format('YYYY-MM-DD HH:mm:ss'),
                end_date: moment(values.end_date).format('YYYY-MM-DD HH:mm:ss'),
                // rtuId: `${fieldsValue.product_code ? '%' + fieldsValue.product_code + '%%-%' : '%'}`,
                rtuId: '%',
              };
              const that = this;
              that.handleSearch(params, true);

            });
          }}>
            <FormattedMessage
              id="form.search"
              defaultMessage="查询"
            />
          </Button>
          <Button icon="redo" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
            <FormattedMessage
              id="form.reset"
              defaultMessage="重置"
            />
          </Button>
        </FormItem>
      </Form>
    );
  }


  renderForm() {
    return this.renderSimpleForm();
    // return ''
  }

  onExpand = (expanded, record) => {
    const expandedKey = this.state.expandedRowKeys;
    if (expandedKey.indexOf(record.device_id + record.timestamp) == -1) {
      expandedKey.push(record.device_id + record.timestamp);
    } else {
      for (let i = 0; i < expandedKey.length; i++) {
        if (expandedKey[i] === record.device_id + record.timestamp) {
          expandedKey.splice(i, 1);
        }
      }
    }
    this.setState({
      expandedRowKeys: expandedKey,        //设置展开行的key值
    });
  };
  renderStatus = (text) => {
    switch (text) {
      case 1:
        return <Tag color="green">下发成功</Tag>;
        break;
      case 2:
        return <Tag color="geekblue">下发等待</Tag>;
        break;
      case 3:
        return <Tag color="#87d068">更新成功</Tag>;
        break;
      case 4:
        return <Tag color="orange">更新失败</Tag>;
        break;
      case 5:
        return <Tag color="red">没有找到最新固件</Tag>;
        break;
      case 6:
        return <Tag color="cyan">当前已是最新版本</Tag>;
        break;
      default:
        return '';
    }
  };
  getOption=()=>{
    const {
      whole_data2: { data, loading, meta, pageLoaded },
    } = this.props;
    let obj={}
    for(let i=0;i<data.length;i++){
      let product_code=data[i].rtuId.split('-')[0]
      if(obj[product_code]){
        obj[product_code]=obj[product_code]+1
      }else{
        obj[product_code]=1
      }
    }
    console.log('obj',obj)
    let xData=[]
    let yData=[]
    let Data=[]
    for(let key in obj){
      Data.push(  {value: obj[key], name: key},)
    }
   let option = {
      animation:false,
      color:['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
     title: {
       text: `总数 ${data.length}`,
       left: 'center',
       bottom:'10%'
     },
     grid: {
       top: '10%',
       left: '5%',
       right: '1%',
       bottom: '4%',
       containLabel: true,
     },
     legend: {
       orient: 'vertical',
       left: 'left',
       top:'10'
     },
     tooltip: {
       trigger: 'item',
       formatter: '{a} <br/>{b}: {c} ({d}%)'
     },
      series: [{
        name: '产品码',
        data: Data,
        type: 'pie',
        radius: '50%',
        labelLine: {
          length: 30,
        },
        label: {
          formatter: '{c|{c}}',
          backgroundColor: '#F6F8FC',
          borderColor: '#8C8D8E',
          borderWidth: 1,
          borderRadius: 4,

          rich: {
            a: {
              color: '#6E7079',
              lineHeight: 22,
              align: 'center'
            },
            hr: {
              borderColor: '#8C8D8E',
              width: '100%',
              borderWidth: 1,
              height: 0
            },
            b: {
              color: '#4C5058',
              fontSize: 14,
              fontWeight: 'bold',
              lineHeight: 33
            },
            c: {
              fontSize: 16,
              padding: [3, 4],
              fontWeight: 'bold',
            },
            per: {
              color: '#fff',
              backgroundColor: '#4C5058',
              padding: [4, 5],
              borderRadius: 4
            }
          }
        },
      }]
    };
    return option
  }
  render() {
    const {
      whole_data2: { data, loading, meta, pageLoaded },
    } = this.props;
    const columns = [
      {
        title: '序号',
        width: 50,
        key: '_index',
        render: (text, record, index) => {
          const {
            whole_data2: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.number) * meta.size) + (index + 1)}</p>;
        },
      },
      {
        title: '产品码',
        dataIndex: 'rtuId',
        key: 'rtuId',
        render: (text, record) => {
          return <p>{text.split('-')[0]}</p>;
        },
      },
      {
        title: '序列号',
        dataIndex: 'rtuId2',
        key: 'rtuId2',
        render: (text, record) => {
          return <p>{record.rtuId.split('-')[1]}</p>;
        },
      },
      {
        title: '当前固件',
        dataIndex: 'currentFirmwareVersion',
        key: 'currentFirmwareVersion',
        render:(text,record)=>{
          return <div>
            <p>版 本 : {text}</p>
            <p>GUID : { record.currentFirmwareGuid}</p>
          </div>
        }
      },
      {
        title: '最新时间',
        dataIndex: 'time',
        key: 'time',
      },
    ];
    let parseData=[]
    for(let i=0;i<data.length;i++){
      if(data[i].rtuId.indexOf(this.state.searchText)===0){
        parseData.push(data[i])
      }
    }
    const renderTable2 = <div>
      <div>
        <Table
          style={{ backgroundColor: '#fff' }}
          className="custom-small-table whole-data"
          loading={loading}
          bordered={true}
          size="small"
          //rowKey={(record)=>record.device_id + record.timestamp+Math.floor(Math.random()*10) }
          rowKey={(record) => record.rtuId}
          dataSource={parseData}
          columns={columns}
          pagination={false}
          //expandedRowKeys={this.state.expandedRowKeys}
        />
      </div>

    </div>;

    const { editRecord } = this.state;
    const that=this
    return (
      <div>
        <div className="page-header">
          <PageHeader
            title={'上线统计'}
          />
        </div>
        <div className="info-page-container  data-desc ">

          <Card>
            <div className={styles.tableList} style={{ padding: '12px' }}>
              <div >{this.renderForm()}</div>
              <ReactEcharts
                option={this.getOption()}
                style={{ height: '550px', width: '100%' }}
                onEvents={{
                  'click': (params)=>{
                    console.log('params.dataIndex',params)
                    that.setState({
                      searchText:params.data.name,
                    })
                  },
                }}
              />
              {this.state.searchText&&renderTable2}
            </div>
          </Card>
        </div>

        <Drawer
          title={`${this.state.editRecord.substrate && this.state.editRecord.substrate.serial_number} 详情`}
          placement="right"
          destroyOnClose
          onClose={() => {
            this.setState({
              detailModal: false,
              editRecord: {},
            });
          }}

          width={550}
          visible={this.state.detailModal}
        >
          <Descriptions column={2} title={<div>
            <span></span>
          </div>} bordered>
            <Descriptions.Item label="序列号"
                               span={2}>{editRecord.substrate ? editRecord.substrate.serial_number : ''}</Descriptions.Item>
            <Descriptions.Item label="RTU基板型号"
                               span={2}>{editRecord.substrate ? editRecord.substrate.substrate_type.name : ''}</Descriptions.Item>
            <Descriptions.Item label="RTU基板产品代码"
                               span={2}>{editRecord.substrate ? editRecord.substrate.substrate_type.product_code : ''}</Descriptions.Item>
            <Descriptions.Item label="状态" span={2}>{this.renderStatus(editRecord.status)}</Descriptions.Item>
            <Descriptions.Item label="当前固件版本" span={2}>{editRecord.current_firmware_version}</Descriptions.Item>
            <Descriptions.Item label="当前固件GUID" span={2}>{editRecord.current_firmware_guid}</Descriptions.Item>
            <Descriptions.Item label="新固件版本" span={2}>{editRecord.new_firmware_version}</Descriptions.Item>
            <Descriptions.Item label="新固件GUID" span={2}>{editRecord.new_firmware_guid}</Descriptions.Item>
            <Descriptions.Item label="创建时间" span={2}>{editRecord.created_at}</Descriptions.Item>

          </Descriptions>
        </Drawer>

      </div>
    );
  }
}

export default TableList;
